package deadLock;

// 模拟死锁
// 死锁：多个线程互相抱着对方需要的资源，形成僵持
// 两个女生化妆，都需要镜子和口红
public class DeadLock {
    public static void main(String[] args) {
        Makeup girl1 = new Makeup("0","小王");
        Makeup girl2 = new Makeup("1","小宋");
        //Makeup girl3 = new Makeup("1","小李");
        girl1.start();
        girl2.start();
        //girl3.start();
    }
}
//口红
class lipstick{}
//镜子
class mirror{}
class Makeup extends Thread{
    // static 来保证只有一个
    static String lipstick = "口红";
    static String mirror = "镜子";
    //static final lipstick lipstick = new lipstick();
    //static final mirror mirror = new mirror();
    private String choice;
    private String girlName;

    public Makeup(String choice, String name) {
        this.choice = choice;
        this.girlName = name;
    }

    @Override
    public void run() {
        try {
            makeUp();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void makeUp() throws InterruptedException {
        switch (choice){
            case "0":
                synchronized (lipstick){  // 如果先选择口红，就获得口红的锁，口红用完了，再获取镜子
                    System.out.println(this.girlName + "获得口红");
                    Thread.sleep(1000);
                    synchronized (mirror){  // 如果口红用完了，不释放口红的锁就去获取镜子的锁，就会发生死锁
                        System.out.println(this.girlName + "获得镜子");
                    }
                }
                //synchronized (mirror){  // 如果口红用完了，释放口红的锁就去获取镜子的锁，就不会发生死锁
                //    System.out.println(this.girlName + "获得镜子");
                //}
                break;
            case "1":
                synchronized (mirror){
                    System.out.println(this.girlName + "获得镜子");
                    Thread.sleep(1000);
                    synchronized (lipstick){
                        System.out.println(this.girlName + "获得口红");
                    }
                }
                //synchronized (lipstick){ // 如果口红用完了，释放口红的锁就去获取镜子的锁，就不会发生死锁
                //    System.out.println(this.girlName + "获得口红");
                //}
                break;
        }
    }
}
